<?php
/**
 * Created by PhpStorm.
 * User: W
 * Date: 2018/2/24
 * Time: 10:36
 */

namespace app\console\controller\goods;

use app\common\controller\Console;

class Cate extends Console
{

    public function index()
    {
        $where  = [];
        $q = request()->get('q');
        if ($q)
            $where['name'] = ['like',"%$q%"];
        $cate_model = model('Cates');
        $list = $cate_model->where($where)->paginate(15);
        $p_cates = $cate_model->where('pid', 0)->select();
        $this->assign([
            'list' => $list,
            'p_cates' => $p_cates
        ]);
        return $this->fetch();
    }

    public function edit($id)
    {
        $model = model('Cates');
        $row = $model->where('id', $id)->find();
        $where = [
            'pid' => 0,
            'id' => ['neq',$id]
        ];
        $p_cates = $model->where($where)->select();
        $this->assign([
            'row' => $row,
            'p_cates' => $p_cates
        ]);
        return $this->fetch();
    }

    public function insert()
    {
        if ($data = request()->post()) {
            if (!$data['name'])
                $this->error('名称不能为空');
            $model = model('Cates');
            $model->data(['name' => $data['name'], 'pid' => $data['pid']])->save();
            $this->success('添加成功');
        }
    }
    
    public function update()
    {
        if ($data = request()->post()) {
            if (!$data['name']) {
                $this->error('名称不能为空');
            }
            $model = model('Cates');
            $model->lock(true)->where('id', $data['id'])->find();
            $model->save(['name' => $data['name'] ,'pid' => $data['pid']], ['id' => $data['id']]);
            $this->success('更新成功', url('index'));
        }
    }

    public function del($id)
    {
        model('Cates')->where('id', $id)->delete();
        return redirect($_SERVER['HTTP_REFERER']);
    }
}
